<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" :footer="null">
    <div class="step-form-container">
      <!-- 步骤条 -->
      <a-steps :current="currentStep" class="step-steps">
        <a-step title="编写文章" description="使用Markdown编辑器编写文章内容" />
        <a-step title="设置信息" description="选择分类、标签等文章信息" />
        <a-step title="发布设置" description="设置文章状态和SEO信息" />
      </a-steps>

      <!-- 第一步：Markdown编辑器 -->
      <div v-show="currentStep === 0" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-form-item label="文章标题" required>
            <a-input v-model:value="formData.title" placeholder="请输入文章标题" />
          </a-form-item>
          <a-form-item label="文章摘要" required>
            <a-textarea v-model:value="formData.excerpt" placeholder="请输入文章摘要，限制100字" :rows="3" :maxlength="100" show-count />
            <div class="form-tip">提示：摘要将用于文章列表和SEO展示，建议控制在100字以内</div>
          </a-form-item>
          <a-form-item label="文章内容" required>
            <Suspense>
              <template #default>
                <JMarkdownEditor v-model:value="formData.content" :height="600" mode="wysiwyg" />
              </template>
              <template #fallback>
                <a-skeleton active :paragraph="{ rows: 16 }" style="height: 600px" />
              </template>
            </Suspense>
          </a-form-item>
        </a-form>
      </div>

      <!-- 第二步：标签信息 -->
      <div v-show="currentStep === 1" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-form-item label="文章分类" required>
            <JDictSelectTag
              v-model:value="formData.categoryId"
              placeholder="请选择文章分类"
              dictCode="blog_categories,name,id"
              style="width: 100%"
              @change="onCategoryChange"
            />
          </a-form-item>
          <a-row :gutter="12">
            <a-col :span="16">
              <a-form-item label="文章标签">
                <a-input v-model:value="formData.tags" placeholder="请输入文章标签，多个标签用逗号分隔" />
                <div class="form-tip">提示：多个标签请用逗号分隔，如：技术,Vue,前端</div>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="文章图标">
                <div class="emoji-form-row">
                  <a-input v-model:value="icon" placeholder="点击右侧图标选择" readonly class="emoji-input" />
                  <template v-if="icon">
                    <a-button type="text" size="small" @click="icon = ''" class="clear-emoji">清除</a-button>
                  </template>
                  <template v-else>
                    <Vue3Emoji size="small" :options-name="optionsName" @click-emoji="selectEmoji" />
                  </template>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="文章颜色">
            <div class="color-selector">
              <div class="color-presets">
                <div
                  v-for="color in colorPresets"
                  :key="color"
                  class="color-option"
                  :style="{ background: color }"
                  :class="{ active: formData.color === color }"
                  @click="formData.color = color"
                ></div>
              </div>
              <div v-if="formData.color" class="selected-color" :style="{ background: formData.color }">
                <span class="color-value">{{ formData.color }}</span>
                <a-button type="text" size="small" @click="formData.color = ''" class="clear-color"> 清除 </a-button>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="排序权重">
            <a-input-number v-model:value="formData.sortOrder" placeholder="请输入排序权重" style="width: 100%" />
          </a-form-item>
        </a-form>
      </div>

      <!-- 第三步：状态设置 -->
      <div v-show="currentStep === 2" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-form-item label="文章状态" required>
            <a-radio-group v-model:value="formData.status">
              <a-radio :value="0">草稿</a-radio>
              <a-radio :value="1">发布</a-radio>
              <a-radio :value="2">下架</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="SEO关键词">
            <a-input v-model:value="formData.seoKeywords" placeholder="请输入SEO关键词，多个关键词用逗号分隔" />
          </a-form-item>
          <a-form-item label="SEO描述">
            <a-textarea v-model:value="formData.seoDescription" placeholder="请输入SEO描述" :rows="3" />
          </a-form-item>
          <a-form-item label="阅读次数">
            <a-input-number v-model:value="formData.readCount" placeholder="请输入阅读次数" style="width: 100%" />
          </a-form-item>
        </a-form>
      </div>

      <!-- 步骤操作按钮 -->
      <div class="step-actions">
        <a-button v-if="currentStep > 0" @click="prevStep">上一步</a-button>
        <a-button v-if="currentStep < 2" type="primary" @click="nextStep">下一步</a-button>
        <a-button v-if="currentStep === 2" type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isUpdate ? '更新' : '保存' }}
        </a-button>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, reactive, defineAsyncComponent, onMounted, defineOptions, nextTick } from 'vue';

  defineOptions({ name: 'BlogArticlesStepForm' });
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { JDictSelectTag } from '/@/components/Form';
  import { saveOrUpdate } from '../BlogArticles.api';
  import { message } from 'ant-design-vue';
  import Vue3Emoji from 'vue3-emoji';
  import { getArticleCategories } from '/@/api/blog/articles';

  // Emits声明
  const emit = defineEmits(['register', 'success']);

  const currentStep = ref(0);
  const submitLoading = ref(false);
  const isUpdate = ref(false);
  const optionsName = {
    'Smileys & Emotion': '表情',
    'Food & Drink': '食物&饮料',
    'Animals & Nature': '动物&自然',
    'Travel & Places': '旅行&地点',
    'People & Body': '人物&身体',
    Objects: '物品',
    Symbols: '符号',
    Flags: '旗帜',
    Activities: '活动',
  };

  // 颜色预设
  const colorPresets = ref([
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', // 蓝紫
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', // 粉红
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', // 绿青
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', // 粉黄
    'linear-gradient(135deg, #30cfd0 0%, #330867 100%)', // 青蓝
    'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)', // 浅蓝
    'linear-gradient(135deg, #f7971e 0%, #ffd200 100%)', // 橙黄
    'linear-gradient(135deg, #f857a6 0%, #ff5858 100%)', // 紫红
    'linear-gradient(135deg, #00c6fb 0%, #005bea 100%)', // 靛蓝
    'linear-gradient(135deg, #fceabb 0%, #f8b500 100%)', // 米黄
    'linear-gradient(135deg, #76b852 0%, #8dc26f 100%)', // 草绿
    'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)', // 紫蓝淡
    'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)', // 灰蓝
    'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)', // 橙粉
    'linear-gradient(135deg, #c471f5 0%, #fa71cd 100%)', // 紫粉
    'linear-gradient(135deg, #48c6ef 0%, #6f86d6 100%)', // 蓝灰
  ]);

  // 分类列表
  const categoryList = ref<any[]>([]);
  onMounted(async () => {
    const res = await getArticleCategories();
    categoryList.value = res?.result || res || [];
  });

  // 表单数据
  const formData = reactive({
    id: '',
    title: '',
    excerpt: '',
    content: '',
    categoryId: null,
    categoryName: null,
    icon: '',
    color: '',
    tags: '',
    readCount: 0,
    status: 0,
    sortOrder: 0,
    seoKeywords: '',
    seoDescription: '',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    delFlag: 0,
  });

  const icon = ref('');

  // 分类选择变化
  function onCategoryChange(value: any) {
    // JDictSelectTag 返回的是 id 值，需要根据 id 找到对应的 name
    const found = categoryList.value.find((item: any) => item.id === value);
    if (found) {
      formData.categoryId = found.id;
      formData.categoryName = found.name;
    } else {
      formData.categoryId = null;
      formData.categoryName = null;
    }
  }

  // 表单配置
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置步骤到第一步
    currentStep.value = 0;

    // 重置表单
    Object.keys(formData).forEach((key) => {
      if (key === 'categoryId' || key === 'categoryName') {
        formData[key] = null;
      } else {
        formData[key] = '';
      }
    });
    formData.status = 0;
    formData.readCount = 0;
    formData.sortOrder = 0;
    formData.delFlag = 0;

    setModalProps({ confirmLoading: false, showCancelBtn: false, showOkBtn: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      // 表单赋值
      Object.keys(data.record).forEach((key) => {
        if (formData.hasOwnProperty(key)) {
          formData[key] = data.record[key];
        }
      });
      icon.value = data.record.icon || '';

      // 分类回显（确保categoryList加载且类型一致）
      await nextTick();

      // 确保分类列表已加载
      if (categoryList.value.length === 0) {
        const res = await getArticleCategories();
        categoryList.value = res?.result || res || [];
      }

      // 查找对应的分类
      const found = categoryList.value.find((item) => {
        // 处理不同的数据类型
        const itemId = String(item.id);
        const formId = String(formData.categoryId);
        return itemId === formId;
      });

      if (found) {
        formData.categoryId = found.id;
        formData.categoryName = found.name;
        console.log('分类回显成功:', found.name, found.id);
      } else {
        console.log('未找到对应分类:', formData.categoryId, '分类列表:', categoryList.value);
      }

      // 标签回显（解析json）
      if (typeof formData.tags === 'string') {
        try {
          console.log('原始tags:', formData.tags);

          // 处理双重JSON编码的情况 ["[\"微服务\"", "\"Java\"]"]
          let tagsStr = formData.tags;
          let parsed = false;

          // 尝试解析JSON
          try {
            const arr = JSON.parse(tagsStr);
            if (Array.isArray(arr)) {
              // 检查数组元素是否还是JSON字符串
              const cleanTags = arr.map((item) => {
                if (typeof item === 'string' && item.startsWith('"') && item.endsWith('"')) {
                  // 去掉引号
                  return item.slice(1, -1);
                }
                return item;
              });
              formData.tags = cleanTags.join(',');
              parsed = true;
            }
          } catch (e) {
            console.log('第一次JSON解析失败:', e);
          }

          // 如果第一次解析失败，尝试直接处理字符串格式
          if (!parsed) {
            // 处理类似 ["微服务","Java"] 的格式
            if (tagsStr.startsWith('[') && tagsStr.endsWith(']')) {
              const cleanTags = tagsStr.replace(/[\[\]"]/g, '');
              formData.tags = cleanTags;
            }
          }

          console.log('处理后的tags:', formData.tags);
        } catch (error) {
          console.error('标签处理失败:', error);
        }
      }
    } else {
      icon.value = '';
    }
  });

  // 设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增文章' : '编辑文章'));

  // 下一步
  const nextStep = () => {
    if (currentStep.value === 0) {
      if (!formData.title.trim()) {
        message.error('请输入文章标题');
        return;
      }
      if (!formData.excerpt.trim()) {
        message.error('请输入文章摘要');
        return;
      }
      if (!formData.content.trim()) {
        message.error('请输入文章内容');
        return;
      }
    } else if (currentStep.value === 1) {
      if (!formData.categoryId) {
        message.error('请选择文章分类');
        return;
      }
    }
    currentStep.value++;
  };

  // 上一步
  const prevStep = () => {
    currentStep.value--;
  };

  // 选择emoji
  const selectEmoji = (val: any) => {
    console.log('选中的emoji', val);
    icon.value = typeof val === 'string' ? val : val.emoji;
  };

  // 表单提交事件
  async function handleSubmit() {
    try {
      // 验证必填字段
      if (!formData.title.trim()) {
        message.error('请输入文章标题');
        return;
      }
      if (!formData.excerpt.trim()) {
        message.error('请输入文章摘要');
        return;
      }
      if (!formData.content.trim()) {
        message.error('请输入文章内容');
        return;
      }
      if (!formData.categoryId) {
        message.error('请选择文章分类');
        return;
      }

      formData.icon = icon.value;
      setModalProps({ confirmLoading: true });
      submitLoading.value = true;

      // 处理tags字段，如果是字符串则转换为JSON数组
      if (formData.tags && typeof formData.tags === 'string') {
        const tagsArray = formData.tags
          .split(',')
          .map((tag) => tag.trim())
          .filter((tag) => tag);
        // 确保保存为正确的JSON格式 ["微服务", "Java"]
        formData.tags = JSON.stringify(tagsArray);
        console.log('提交的tags:', formData.tags);
      }

      // 提交表单
      await saveOrUpdate(formData, isUpdate.value);

      // 关闭弹窗
      closeModal();
      // 刷新列表
      emit('success');
      message.success(isUpdate.value ? '更新成功' : '保存成功');
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setModalProps({ confirmLoading: false });
      submitLoading.value = false;
    }
  }

  const JMarkdownEditor = defineAsyncComponent(
    () =>
      new Promise((resolve) => {
        setTimeout(() => {
          resolve(import('/@/components/Form/src/jeecg/components/JMarkdownEditor.vue'));
        }, 3000); // 故意延迟3秒
      })
  ) as any;
</script>

<style lang="less" scoped>
  .step-form-container {
    padding: 12px 0 0 0;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    min-height: 420px;
    max-width: 700px;
    margin: 0 auto;
    @media (max-width: 600px) {
      padding: 4px 0 0 0;
      min-height: 320px;
      border-radius: 0;
      max-width: 100vw;
    }
  }
  .step-steps {
    margin-bottom: 18px;
    background: transparent;
    border-radius: 0;
    padding: 0;
    box-shadow: none;
    :deep(.ant-steps-item-process .ant-steps-item-icon) {
      background: #3b82f6;
      border-color: #3b82f6;
      box-shadow: none;
    }
    :deep(.ant-steps-item-process .ant-steps-item-title) {
      color: #3b82f6;
      font-weight: 500;
      letter-spacing: 0.5px;
    }
    :deep(.ant-steps-item-title) {
      font-size: 15px;
      color: #888;
      font-weight: 400;
    }
    :deep(.ant-steps-item-description) {
      color: #b0b0b0;
      font-size: 12px;
    }
  }
  .step-content {
    min-height: 320px;
    padding: 0;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    margin-bottom: 0;
    @media (max-width: 600px) {
      padding: 0;
      min-height: 180px;
    }
    a-form {
      padding: 0 16px;
      @media (max-width: 600px) {
        padding: 0 2px;
      }
    }
  }
  .step-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: #222;
    border: none;
    padding-bottom: 0;
    letter-spacing: 0.5px;
    text-align: left;
    padding-left: 16px;
    @media (max-width: 600px) {
      padding-left: 4px;
    }
  }
  .step-actions {
    text-align: center;
    margin-top: 18px;
    padding: 0 16px 16px 16px;
    border: none;
    background: transparent;
    border-radius: 0;
    .ant-btn {
      margin: 0 6px;
      min-width: 90px;
      font-size: 14px;
      border-radius: 18px;
      height: 34px;
      box-shadow: none;
      border: none;
      font-weight: 500;
      background: #f3f4f6;
      color: #222;
      transition: all 0.18s;
      &:hover {
        background: #e0e7ef;
        color: #2563eb;
      }
      &:active {
        background: #dbeafe;
        color: #2563eb;
      }
    }
    .ant-btn-primary {
      background: linear-gradient(90deg, #3b82f6 60%, #2563eb 100%);
      color: #fff;
      font-weight: 600;
      box-shadow: none;
      border: none;
      &:hover,
      &:active {
        background: linear-gradient(90deg, #2563eb 60%, #3b82f6 100%);
        color: #fff;
      }
    }
  }
  .form-tip {
    font-size: 12px;
    color: #b0b0b0;
    margin-top: 2px;
  }
  :deep(.ant-form-item) {
    margin-bottom: 18px;
  }
  :deep(.ant-input),
  :deep(.ant-input-number),
  :deep(.ant-textarea) {
    border-radius: 8px;
    font-size: 15px;
    min-height: 32px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    box-shadow: none;
    transition: border 0.18s;
    &:focus,
    &:hover {
      border-color: #3b82f6;
      background: #fff;
    }
  }
  :deep(.ant-input-number) {
    width: 100%;
  }
  :deep(.ant-radio-group) {
    font-size: 15px;
    .ant-radio-inner {
      border-radius: 50%;
      border-color: #d1d5db;
    }
    .ant-radio-checked .ant-radio-inner {
      border-color: #3b82f6;
      background: #3b82f6;
    }
  }
  :deep(.ant-form-item-label > label) {
    font-weight: 400;
    color: #888;
    letter-spacing: 0.2px;
    font-size: 14px;
  }

  .emoji-form-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .emoji-input {
    flex: 2;
    min-width: 200px;
    max-width: 320px;
  }
  .emoji-trigger {
    cursor: pointer;
  }
  .clear-emoji {
    color: #999;
    margin-left: 4px;
  }
  .emoji-preview {
    font-size: 18px;
  }

  .color-selector {
    .color-presets {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      flex-wrap: wrap;
      .color-option {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        cursor: pointer;
        border: 3px solid #fff; // 白色内边框，保证渐变色下清晰
        box-shadow: 0 0 0 1.5px #d1d5db; // 外发光，提升对比度
        transition: all 0.2s;
        position: relative;
        background-clip: padding-box;
        &:hover {
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;
          border-color: #2563eb;
        }
        &.active {
          border-color: #2563eb;
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;
          &::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            font-size: 14px;
            font-weight: bold;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
            pointer-events: none;
          }
        }
      }
    }
    .selected-color {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
      font-size: 12px;
      min-height: 40px;
      position: relative;
      overflow: hidden;
      .color-value {
        font-weight: 500;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .clear-color {
        color: rgba(255, 255, 255, 0.9);
        background: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        padding: 2px 6px;
        &:hover {
          color: white;
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
  }

  .emoji-picker-inline {
    min-height: 320px;
    max-height: 420px;
    margin-top: 8px;
    border-radius: 8px;
    background: #f8fafc;
    overflow-y: auto;
    padding: 8px 0;
    :deep(.vue3-emoji) {
      border: none;
      background: transparent;
    }
  }

  :deep([class*='emojiItem']) {
    width: auto !important;
  }

  .emoji-input {
    width: 220px;
    min-width: 0;
    max-width: none;
    flex: none;
  }
</style>
